package com.dd.ent.car.common.xrichtext.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.dd.ent.car.AppContext;
import com.dd.ent.car.R;
import com.dd.ent.car.common.bean.base.PageBean;
import com.dd.ent.car.common.bean.base.ResultBean;
import com.dd.ent.car.common.bean.comment.Comment;
import com.dd.ent.car.common.config.UIConfig;
import com.dd.ent.car.common.util.DateUtils;
import com.dd.ent.car.common.util.StringUtils;
import com.dd.ent.car.common.xrichtext.EditData;
import com.dd.ent.car.common.xrichtext.RichTextView;
import com.dd.ent.car.common.bean.note.Note;
import com.dd.ent.car.service.comment.CommentService;
import com.dd.ent.car.service.note.NoteService;
import com.dd.ent.car.service.user.UserService;
import com.dd.ent.car.ui.detail.DetailBottomView;
import com.dd.ent.car.ui.detail.DetailCommentView;
import com.dd.ent.car.ui.user.LoginActivity;
import com.dd.ent.car.ui.user.note.ImageDialogActivity;
import com.dd.ent.car.ui.widget.CommentDialog;
import com.google.gson.reflect.TypeToken;
import com.pp.ent.Cherry;
import com.pp.ent.base.concurrent.XLCommand;
import com.pp.ent.base.concurrent.XLCommandListener;
import com.pp.ent.base.concurrent.XLCommandResult;
import com.pp.ent.base.concurrent.XLThreadPool;
import com.pp.ent.base.log.MLog;
import com.pp.ent.core.manage.UIHandler;
import com.pp.ent.view.annotation.ContentView;
import com.pp.ent.view.annotation.Inject;
import com.pp.ent.view.annotation.OnClick;
import com.pp.ent.view.annotation.ViewInject;
import com.qiniu.android.http.ResponseInfo;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.dd.ent.car.common.config.UIConfig.ADD_PLAY_COUNT_TO_NOTE_SUCCESS;
import static com.dd.ent.car.common.config.UIConfig.NOTIFY_NOTE_UPDATE_COMMENT_COUNT;
import static com.dd.ent.car.common.config.UIConfig.NOTIFY_NOTE_UPDATE_VISIT_COUNT;
import static com.pp.ent.core.manage.CoreManager.getContext;

/**
 * 笔记详情
 */
@ContentView(R.layout.activity_note)
public class NoteActivity extends com.dd.ent.car.ui.BaseActivity implements DetailBottomView.SendCommentListener {

    public final static String NOTES = "notes";
    public final static String NOTE = "note";
    public final static String FROM = "from";


    @ViewInject(R.id.tv_note_title)
    private TextView tv_note_title;//笔记标题

    @ViewInject(R.id.tv_note_content)
    private RichTextView tv_note_content;//笔记内容

    @ViewInject(R.id.titlebar_left)
    private ImageView titlebarLeft;

    @ViewInject(R.id.titlebar_title)
    private TextView titlebarTitle;

    @ViewInject(R.id.titlebar_right_tv1)
    private TextView titlebarRightTv1;

    @ViewInject(R.id.detail_bottom_view)
    private DetailBottomView detailBottomView;

    @Inject
    private NoteService noteService;
    @Inject
    private UserService userService;
    @Inject
    private CommentService commentService;

    private List<EditData> editDatas;
    private Note note;//笔记对象
    private From from;
    private String myTitle;
    private String myContent;
    private String myGroupName;

    private ProgressDialog loadingDialog;
    private Subscription subsLoading;
    private ProgressDialog mProgressDialog;
    private CommentDialog mCommentDialog;
    private List<Comment> comments;

    public static void startSelf(Context context, From from, Note note) {
        Intent intent1 = new Intent(context, NoteActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(NOTE, note);
        bundle.putSerializable(FROM, from);
        intent1.putExtra("data", bundle);
        context.startActivity(intent1);
    }


    public enum From {
        PUBLISH,
        DETAILS,
        FORUM
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleIntent();
        initData();

    }

    private void handleIntent() {
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("data");
        note = (Note) bundle.getSerializable(NOTE);
        from = (From) bundle.getSerializable(FROM);
    }

    private void initData() {
        loadingDialog = new ProgressDialog(this);
        loadingDialog.setMessage("数据加载中...");
        loadingDialog.setCanceledOnTouchOutside(false);
        tv_note_title.setTextIsSelectable(true);
        myTitle = note.getTitle();
        editDatas = NewActivity.editDatas;
        if (from == From.PUBLISH) {
            myContent = getEditData();
        } else {
            myContent = note.getContent();
        }
        tv_note_title.setText(myTitle);
        tv_note_content.post(new Runnable() {
            @Override
            public void run() {
                tv_note_content.clearAllLayout();
                showDataSync(myContent);
            }
        });
        titlebarTitle.setText("贴文详情");
        switch (from) {
            case PUBLISH:
                initPublishState();
                break;
            case FORUM:
            case DETAILS:
                initDetailsState();
                break;
        }


    }

    private void addNoteHeaderView() {
        NoteHeaderView noteHeaderView = new NoteHeaderView(this);
        noteHeaderView.refreshNote(note);
        tv_note_content.addViewAtIndex(noteHeaderView, 0);
    }

    private void initPublishState() {
        titlebarRightTv1.setText("发布");
        titlebarRightTv1.setVisibility(View.VISIBLE);
        detailBottomView.setVisibility(View.GONE);
    }

    private void initDetailsState() {
        titlebarRightTv1.setVisibility(View.GONE);
        detailBottomView.setVisibility(View.VISIBLE);
        detailBottomView.setSendCommentListener(this);
        sumbitNoteInfo();
    }

    @Override
    public void onSend(CharSequence content) {
        onSend(content, 0, null);
    }


    public void onSend(CharSequence content, int position, Comment originComment) {
        Comment comment = new Comment();
        comment.setUser(userService.getUser());
        comment.setContent(content.toString());
        comment.setOriginComment(originComment);
        comment.setCreateTime(System.currentTimeMillis());
        int commentCount = comments == null ? 0 : comments.size();
        if (comments == null){
            comments = new ArrayList<>();
        }
        comments.add(comment);
        int insertPosition = tv_note_content.getViewCount() - commentCount;
        tv_note_content.addDetailCommentView(NoteActivity.this, insertPosition, comment, new DetailCommentView.OnCommentItemListener() {
            @Override
            public void onItemClick(int position, Comment comment) {
                if (userService.isLogin()) {
                    showCommentDialog(position, comment);
                } else {
                    LoginActivity.startActivity(NoteActivity.this);
                }
            }
        });
        String originCommentId = originComment == null ? "" : originComment.getUuid();
        commentService.sumbitComment(comment, note, userService.getUid(), originCommentId);
        hideSoftInput();
    }

    private void loadNoteComment() {
        commentService.queryNoteCommentById(note.getUuid());
    }

    private void sumbitNoteInfo() {
        noteService.sumbitPlayCountToNote(note.getUuid(), 1);
    }

    private void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    @OnClick({R.id.titlebar_left, R.id.titlebar_right_tv1})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.titlebar_left:
                onBackPressed();
                break;
            case R.id.titlebar_right_tv1:
                showProgressDialog(R.string.loading);
                sumbitNoteToServer();
                break;
        }
    }

    private void sumbitNoteToServer() {
        XLThreadPool.sendCommand(new XLCommand() {
            @Override
            protected Object excute() throws Exception {
                return sumbitPicture();
            }
        }, new XLCommandListener() {
            @Override
            public void onResponse(XLCommandResult xlCommandResult) {
                if (xlCommandResult != null && xlCommandResult.isSuccessful()) {
                    note.setContent((String) xlCommandResult.data);
                    note.setUpdateTime(DateUtils.date2string(new Date()));
                    noteService.sumbitNote(note, userService.getUid());
                } else {
                    showToast("发布失败！");
                }
            }
        });
    }

    /**
     * 负责处理编辑数据提交等事宜，请自行实现
     */
    private String getEditData() {
        StringBuffer content = new StringBuffer();
        for (EditData itemData : editDatas) {
            if (itemData.inputStr != null) {
                content.append(itemData.inputStr);
                //Log.d("RichEditor", "commit inputStr=" + itemData.inputStr);
            } else if (itemData.imagePath != null) {
                //Log.d("RichEditor", "commit imgePath=" + itemData.imagePath);
                //imageList.add(itemData.imagePath);
                //// ResponseInfo responseInfo = new VideoService().syncSumbitFile((itemData.imagePath));
                // MLog.debug("getEditData", responseInfo.path);
                // String playUrl = "http://quydbezgk.hn-bkt.clouddn.com/" + responseInfo.response.optString("hash");
                content.append("<img src=\"").append(itemData.imagePath).append("\"/>");
            }
        }
        return content.toString();
    }

    /**
     * 负责处理编辑数据提交等事宜，请自行实现
     */
    private String sumbitPicture() {
        StringBuffer content = new StringBuffer();
        for (EditData itemData : editDatas) {
            if (itemData.inputStr != null) {
                content.append(itemData.inputStr);
                //Log.d("RichEditor", "commit inputStr=" + itemData.inputStr);
            } else if (itemData.imagePath != null) {
                //Log.d("RichEditor", "commit imgePath=" + itemData.imagePath);
                //imageList.add(itemData.imagePath);
                String playUrl;
                File file = new File(itemData.imagePath);
                if (file != null && file.exists()) {
                    ResponseInfo responseInfo = noteService.syncSumbitFile((itemData.imagePath));
                    MLog.debug("getEditData", responseInfo.path);
                    playUrl = "http://quydbezgk.hn-bkt.clouddn.com/" + responseInfo.response.optString("hash");
                } else {
                    playUrl = itemData.imagePath.trim();
                }
                content.append("<img src=\"").append(playUrl).append("\"/>");
            }
        }
        return content.toString();
    }

    /**
     * 异步方式显示数据
     *
     * @param html
     */
    private void showDataSync(final String html) {
        loadingDialog.show();
        subsLoading = Observable.create(new Observable.OnSubscribe<EditData>() {
            @Override
            public void call(Subscriber<? super EditData> subscriber) {
                showEditData(subscriber, html);
            }
        })
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())//生产事件在io
                .observeOn(AndroidSchedulers.mainThread())//消费事件在UI线程
                .subscribe(new Observer<EditData>() {

                    @Override
                    public void onCompleted() {
                        loadingDialog.dismiss();
                        addNoteHeaderView();
                        if (from != From.PUBLISH) {
                            loadNoteComment();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        loadingDialog.dismiss();
                        e.printStackTrace();
                        showToast("解析错误：图片不存在或已损坏");
                    }

                    @Override
                    public void onNext(final EditData editData) {
                        if (editData.imagePath != null) {
                            tv_note_content.addImageViewAtIndex(tv_note_content.getLastIndex(), editData.imagePath, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    ImageDialogActivity.startSelf(NoteActivity.this, editData.imagePath);
                                }
                            });
                        } else {
                            tv_note_content.addTextViewAtIndex(tv_note_content.getLastIndex(), editData.inputStr);
                        }
                    }
                });
    }

    /**
     * 显示数据
     *
     * @param html
     */
    private void showEditData(Subscriber<? super EditData> subscriber, String html) {
        try {
            List<String> textList = StringUtils.cutStringByImgTag(html);
            for (int i = 0; i < textList.size(); i++) {
                String text = textList.get(i);
                EditData editData = new EditData();
                if (text.contains("<img") && text.contains("src=")) {
                    String imagePath = StringUtils.getImgSrc(text);
                    editData.imagePath = imagePath;
                    //if (new File(imagePath).exists()) {
                    subscriber.onNext(editData);
                    //} else {
                    //     showToast("图片" + 1 + "已丢失，请重新插入！");
                    // }
                } else {
                    editData.inputStr = text;
                    subscriber.onNext(editData);
                }
            }
            subscriber.onCompleted();
        } catch (Exception e) {
            e.printStackTrace();
            subscriber.onError(e);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    protected void dismissProgressDialog() {
        if (null != mProgressDialog) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    protected void showProgressDialog(int message) {
        dismissProgressDialog();
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setMessage(getResources().getString(message));
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }


    private void showCommentDialog(final int position, final Comment comment) {
        if (mCommentDialog == null) {
            mCommentDialog = new CommentDialog(this);
            if (comment != null) {
                mCommentDialog.setContentHint("回复：" + comment.getUserName());
            }
            mCommentDialog.setOnSendButtonClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (v.getId()) {
                        case R.id.btn_send:
                            handleSendComment(v, position, comment);
                            break;
                    }

                }
            });
        }
        if (!mCommentDialog.isShowing()) {
            mCommentDialog.show();
        }
    }


    private void handleSendComment(View v, int position, Comment comment) {
        if (mCommentDialog != null) {
            onSend(mCommentDialog.getContent(), position, comment);
            mCommentDialog.dismiss();
            mCommentDialog = null;
        }

    }

    @UIHandler(UIConfig.ADD_NOTE_INFO_TO_SERVER_SUCCESS)
    public void addNoteInfoServerSuccessResponse() {
        dismissProgressDialog();
        Toast.makeText(this, "上传成功", Toast.LENGTH_LONG).show();
        finish();
    }

    @UIHandler(UIConfig.ADD_NOTE_INFO_TO_SERVER_FAIL)
    public void addNoteInfoServerFailResponse() {
        dismissProgressDialog();
        Toast.makeText(this, "上传失败", Toast.LENGTH_LONG).show();
    }

    @UIHandler(UIConfig.QUERY_COMMENT_BY_NOTE_ID_SUCCESS)
    public void queryCommentSuccessResponse(String json) {
        ResultBean<PageBean<Comment>> resultBean = AppContext.createGson().fromJson(json, getType());
        comments = resultBean.getResult().getItems();
        if (comments != null && !comments.isEmpty()) {
            for (Comment comment : comments) {
                tv_note_content.addDetailCommentView(NoteActivity.this, comment, new DetailCommentView.OnCommentItemListener() {
                    @Override
                    public void onItemClick(int position, Comment comment) {
                        if (userService.isLogin()) {
                            showCommentDialog(position, comment);
                        } else {
                            LoginActivity.startActivity(NoteActivity.this);
                        }

                    }
                });
            }
        }
    }


    @UIHandler(UIConfig.ADD_COMMENT_TO_NOTE_SUCCESS)
    public void addCommentToNoteSuccessResponse() {
        Toast.makeText(this, "评论成功", Toast.LENGTH_LONG).show();
        if (note != null) {
            note.setCommentCount(note.getCommentCount() + 1);
            Cherry.notifyUI(NOTIFY_NOTE_UPDATE_COMMENT_COUNT, note);
        }
    }

    @UIHandler(ADD_PLAY_COUNT_TO_NOTE_SUCCESS)
    public void addVisitToNoteSuccessResponse() {
        if (note != null) {
            note.setVisitCount(note.getVisitCount() + 1);
            Cherry.notifyUI(NOTIFY_NOTE_UPDATE_VISIT_COUNT, note);
        }
    }

    protected Type getType() {
        return new TypeToken<ResultBean<PageBean<Comment>>>() {
        }.getType();
    }

}
